document.addEventListener('DOMContentLoaded', function() {
    // 初始化日期选择器
    $('#dateRange').daterangepicker({
        locale: {
            format: 'YYYY-MM-DD',
            applyLabel: '确定',
            cancelLabel: '取消',
            fromLabel: '从',
            toLabel: '至',
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月']
        },
        startDate: moment().subtract(30, 'days'),
        endDate: moment()
    });

    // 初始化图表
    initializeCharts();
    
    // 加载用户数据
    loadUserSegments();

    // 绑定事件监听器
    $('#applyFilter').on('click', applyFilters);
    $('#addCondition').on('click', addConditionField);
    $('#saveSegment').on('click', saveSegment);

    // 处理侧边栏选中状态
    const listItems = document.querySelectorAll('.list-group-item');
    
    listItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有项的选中状态
            listItems.forEach(i => {
                i.style.backgroundColor = '';
                i.style.color = '#000000';
            });
            
            // 设置当前项的选中状态
            this.style.backgroundColor = '#F5F9FF';
            this.style.color = '#000000';
        });
    });
});

// 初始化图表
function initializeCharts() {
    // 用户分布饼图
    const distributionCtx = document.getElementById('userDistributionChart').getContext('2d');
    window.userDistributionChart = new Chart(distributionCtx, {
        type: 'pie',
        data: {
            labels: ['高价值客户', '潜在客户', '活跃客户', '流失客户'],
            datasets: [{
                data: [0, 0, 0, 0],
                backgroundColor: [
                    '#FF6384',
                    '#36A2EB',
                    '#FFCE56',
                    '#4BC0C0'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'right'
                }
            }
        }
    });

    // 消费趋势折线图
    const trendCtx = document.getElementById('consumptionTrendChart').getContext('2d');
    window.consumptionTrendChart = new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '平均消费金额',
                data: [],
                borderColor: '#36A2EB',
                tension: 0.1,
                fill: false
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '¥' + value;
                        }
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
}

// 加载用户分群数据
function loadUserSegments() {
    fetch('/api/user_segments')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            updateStatistics(data.statistics);
            updateCharts(data.charts);
            updateUserTable(data.users);
        })
        .catch(error => {
            console.error('Error loading user segments:', error);
            showToast('加载用户分群数据失败', 'error');
        });
}

// 更新统计数据
function updateStatistics(statistics) {
    document.getElementById('vipCount').textContent = statistics.vip.count;
    document.getElementById('vipPercentage').textContent = statistics.vip.percentage + '%';
    document.getElementById('potentialCount').textContent = statistics.potential.count;
    document.getElementById('potentialPercentage').textContent = statistics.potential.percentage + '%';
    document.getElementById('activeCount').textContent = statistics.active.count;
    document.getElementById('activePercentage').textContent = statistics.active.percentage + '%';
    document.getElementById('churnCount').textContent = statistics.churn.count;
    document.getElementById('churnPercentage').textContent = statistics.churn.percentage + '%';
}

// 更新图表数据
function updateCharts(chartData) {
    // 更新用户分布图
    window.userDistributionChart.data.datasets[0].data = [
        chartData.distribution.vip,
        chartData.distribution.potential,
        chartData.distribution.active,
        chartData.distribution.churn
    ];
    window.userDistributionChart.update();

    // 更新消费趋势图
    window.consumptionTrendChart.data.labels = chartData.trend.labels;
    window.consumptionTrendChart.data.datasets[0].data = chartData.trend.values;
    window.consumptionTrendChart.update();
}

// 更新用户表格
function updateUserTable(users) {
    const tbody = document.querySelector('#userSegmentTable tbody');
    tbody.innerHTML = '';

    users.forEach(user => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${user.username}</td>
            <td>${user.membership_level}</td>
            <td>¥${user.total_consumption.toFixed(2)}</td>
            <td>${user.last_checkin}</td>
            <td>${user.checkin_count}</td>
            <td><span class="badge bg-${getSegmentBadgeColor(user.segment)}">${user.segment}</span></td>
            <td>
                <button class="btn btn-sm btn-outline-primary" onclick="viewUserDetails(${user.id})">
                    查看详情
                </button>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 应用筛选条件
function applyFilters() {
    const filters = {
        dateRange: $('#dateRange').val(),
        amountRange: $('#amountRange').val(),
        membershipLevel: $('#membershipLevel').val()
    };

    fetch('/api/user_segments/filter', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(filters)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        updateStatistics(data.statistics);
        updateCharts(data.charts);
        updateUserTable(data.users);
        showToast('筛选条件已应用', 'success');
    })
    .catch(error => {
        console.error('Error applying filters:', error);
        showToast('应用筛选条件失败', 'error');
    });
}

// 添加分群条件字段
function addConditionField() {
    const container = document.getElementById('conditionContainer');
    const conditionDiv = document.createElement('div');
    conditionDiv.className = 'condition-item mb-2';
    conditionDiv.innerHTML = `
        <div class="row">
            <div class="col-md-4">
                <select class="form-control" name="field">
                    <option value="consumption">消费金额</option>
                    <option value="checkin_count">入住次数</option>
                    <option value="last_checkin">最近入住</option>
                    <option value="membership_level">会员等级</option>
                </select>
            </div>
            <div class="col-md-3">
                <select class="form-control" name="operator">
                    <option value="gt">大于</option>
                    <option value="lt">小于</option>
                    <option value="eq">等于</option>
                </select>
            </div>
            <div class="col-md-4">
                <input type="text" class="form-control" name="value">
            </div>
            <div class="col-md-1">
                <button type="button" class="btn btn-outline-danger btn-sm" onclick="this.parentElement.parentElement.parentElement.remove()">
                    <i class="mdi mdi-delete"></i>
                </button>
            </div>
        </div>
    `;
    container.appendChild(conditionDiv);
}

// 保存用户分群
function saveSegment() {
    const name = document.getElementById('segmentName').value.trim();
    if (!name) {
        showToast('请输入分群名称', 'warning');
        return;
    }

    const conditions = [];
    document.querySelectorAll('.condition-item').forEach(item => {
        const field = item.querySelector('[name="field"]').value;
        const operator = item.querySelector('[name="operator"]').value;
        const value = item.querySelector('[name="value"]').value.trim();
        
        if (!value) {
            showToast('请填写完整的分群条件', 'warning');
            return;
        }
        
        conditions.push({ field, operator, value });
    });

    if (conditions.length === 0) {
        showToast('请至少添加一个分群条件', 'warning');
        return;
    }

    fetch('/api/user_segments/create', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name: name,
            conditions: conditions
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            $('#createSegmentModal').modal('hide');
            showToast(data.message, 'success');
            loadUserSegments();  // 重新加载数据
        } else {
            showToast(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error saving segment:', error);
        showToast('保存分群失败', 'error');
    });
}

// 查看用户详情
function viewUserDetails(userId) {
    window.location.href = `/user-profile/${userId}`;
}

// 获取分群标签颜色
function getSegmentBadgeColor(segment) {
    switch (segment) {
        case '高价值客户':
            return 'danger';
        case '潜在客户':
            return 'primary';
        case '活跃客户':
            return 'warning';
        case '流失客户':
            return 'info';
        default:
            return 'secondary';
    }
}

// 显示提示消息
function showToast(message, type = 'info') {
    const toast = document.getElementById('toast');
    const toastBody = toast.querySelector('.toast-body');
    
    // 设置消息内容
    toastBody.textContent = message;
    
    // 设置样式
    toast.className = `toast bg-${type === 'error' ? 'danger' : type}`;
    
    // 显示 Toast
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}
